define( [
	'require',
	'jquery',
	'header',
	'nav',
	'tooltip',
	'usergroup_manage',
	'api',
	'message',
	'pagination',
	'blocksit',
	'constants',
	'bigwe_utils',
	'sendPreview',
	'plat_public',
	'unauthor',
	'bigwe_component',
], function( require, $ ) {
	var groupManage = require( 'usergroup_manage' ),
		InterFace = require( 'api' ),
		message = require( 'message' ),
		pagination = require( 'pagination' ),
		route = require( 'constants' ),
		utils = require( 'bigwe_utils' ),
		sp = require( 'sendPreview' ),
		definedCallback = require( 'plat_public' ),
		bwAuthor = require( 'unauthor' ),
		bc = require( 'bigwe_component' );

	var groupManageConfig = {
		requestType: 'post',
		addNewUrl: InterFace.MYMPNEWS.ADD_GROUP,
		addParamName: 'cgn', // 添加分组的参数名
		deleteUrl: InterFace.MYMPNEWS.DEL_GROUP,
		deleteParamName: 'mpnews_custom_id', // 删除分组的参数名
		modifyUrl: InterFace.MYMPNEWS.EDIT_GROUP,
		modifyParam: { // 修改分组的参数名
			groupId: 'mpnews_custom_id',
			groupName: 'group_name'
		},
		userGroupData: null, // 未加载请定义成null 加载完成如果没有数据赋值成空数组
		// 列表展示数据赋值
		deleteCallback: function( data, deleteID ) {
			if ( deleteID && ( $( ".tool_s" ).find( 'span[data-cgid="' + deleteID + '"]' ).hasClass( 'green' ) || $( 'select.group_more' ).val() == deleteID ) ) {
				$( '.group_list > span' ).eq( 0 ).trigger( 'click' )
			} else {
				art_group_id = $( '.group_list' ).find( 'span.green' ).data( 'cgid' ) || $( 'select.group_more' ).val();
			}
			group_list( this.userGroupData );
		},
		addCallback: function( data ) {
			art_group_id = $( '.group_list' ).find( 'span.green' ).data( 'cgid' ) || $( 'select.group_more' ).val();
			group_list( this.userGroupData );
			if ( data_art_id ) {
				cg( data_art_id, data.id );
				data_art_id = '';
			}
		},
		modifyCallback: function() {
			art_group_id = $( '.group_list' ).find( 'span.green' ).data( 'cgid' ) || $( 'select.group_more' ).val();
			group_list( this.userGroupData );
		}
	};
	groupManage.init( groupManageConfig );

	var param = {
		data: {
			p: 1,
			l: 9,
		},
		page: true,
	};
	var group_first_load = true,
		art_group_id,
		data_art_id,
		art_data;
	var content = $( '.main_left' );
	$( '.selectpicker' ).selectpicker();

	function initialize( param ) {
		message.show( '正在加载...' );
		$.ajax( {
			type: 'post',
			url: InterFace.MYMPNEWS.GET_FULL_MSG,
			data: param.data,
			success: function( data ) {
				var data = typeof data ? $.parseJSON( data ) : data;
				if ( data.ret == 0 ) {
					if ( group_first_load ) {
						groupManageConfig.userGroupData = data.data.customs;
						group_list( data.data.customs );
						group_first_load = false;
					};
					mpnews_list( data.data.list );
					$( '.altogether .total_number' ).text( data.data.total );
				}
			},
			complete: function( data ) {
				message.hide();
				$( '[data-toggle="tooltip"]' ).tooltip( {
					trigger: 'hover'
				} );
				content.find( '.graph_list' ).BlocksIt( {
					numOfCol: 3,
					offsetX: 5,
					offsetY: 5
				} );
				var json = typeof data.responseText === 'string' ? $.parseJSON( data.responseText ) : data.responseText;
				if ( param.page ) {
					( json.data.total > 9 ) ? ( $( '.paging' ).show(), paging( json.data.total ) ) : ( $( '.paging' ).hide(), param.page = false );
				}
			},
			error: function() {
				message.showWarning( '数据拉取失败', message.showTime );
			}
		} )
	}

	function mpnews_list( data ) {
		var html = '';
		var _manager = content.find( '.batch_manager' ).data( 'manager' );
		if ( data.length > 0 ) {
			art_data = data;
			for ( var i in data ) {
				var arts = data[ i ].articles;
				html += '<div class="graph_item' + ( _manager ? ' active' : '' ) + '" data-cd="' + data[ i ].article_group + '" data-title="' + arts[ 0 ].title + '">'
				for ( var j in arts ) {
					if ( j == 0 ) {
						html += '<div class="item_row_1"><p class="item_time">' + new Date( data[ i ].create_time ).format( 'yyyy-MM-dd' );
						if ( data[ i ].is_complete ) {
							html += '<span class="pull-right iconfont icon-tongbu1 synchro" data-toggle="tooltip" title="同步到微信"></span>'
						} else {
							html += '<span class="pull-right red">不完整</span>'
						}
						html += '</p>';
						if ( arts[ j ].title ) {
							html += '<a class="item_title' + ( ( arts.length > 1 ) ? ' item_gray' : '' ) + '" target="_blank" href="/article/index/p/' + arts[ j ].cd + '">' + arts[ j ].title + '</a>';
						}
						html += '<img src="' + utils.imgTimthumb( ( arts[ j ].cover || '' ), 279, 160 ) + '" onerror="this.src=\'' + route.resPath + '/images/cover_l.png\';"></div>'
					} else {
						html += '<div class="item_row_2"><table><tr><td><img src="' + utils.imgTimthumb( ( arts[ j ].cover || '' ), 60, 60 ) + '" onerror="this.src=\'' + route.resPath + '/images/cover_s.png\';"></td><td><a href="/article/index/p/' + arts[ j ].cd + '" target="_blank">' + arts[ j ].title + '</a></td></tr></table></div>'
					}
				}
				html += '<div class="item_btn" data-articleid="' + data[ i ].article_group + '" data-id="' + data[ i ].article_group + '" data-title="' + data[ i ].articles[ 0 ].title + '" data-img="' + data[ i ].articles[ 0 ].cover + '"><a href="edit_text?article_group=' + data[ i ].article_group + '" class="iconfont icon-bianji" data-toggle="tooltip" title="编辑"></a>';
				if ( data[ i ].is_complete ) {
					html += '<a href="javascript:void(0)" class="iconfont icon-yulan1 preview" data-toggle="tooltip" title="预览"></a><a href="sending?article_group=' + data[ i ].article_group + '" class="iconfont release_btn ' + ( ( data[ i ].send_bigwis == 0 ) ? 'icon-tongbufasong' : 'icon-38' ) + '" data-toggle="tooltip" title="分发"></a><a href="javascript:void(0)" class="iconfont icon-hebingqi" title="加入合成器" data-toggle="tooltip" addcar-event></a><a href="javascript:void(0)" class="iconfont icon-icon more"><div class="more_moadl"><span class="copy_a">复制</span><span class="move_btn">移动分组</span><span class="delete_single">删除</span></div></a>';
				} else {
					html += '<a href="javascript:void(0)" class="iconfont icon-shanchu item_delete" data-toggle="tooltip" title="删除"></a>'
				}
				html += '</div><div class="print_masking' + ( _manager ? ' fade' : '' ) + '"><div class="backdrop"></div><span class="iconfont icon-zhengque hide"></span></div>';
				html += '</div>';
			}
		} else {
			html = '<p class="content_is_empty"><span class="glyphicon glyphicon-flash"></span>暂无图文</p>'
		}
		content.find( '.graph_list' ).empty().append( html ).BlocksIt( {
			numOfCol: 3,
			offsetX: 5,
			offsetY: 5
		} );
	}

	function paging( number ) {
		var curent_page = param.data.p - 1;
		$( '.paging' ).pagination( number, {
			num_edge_entries: 2,
			items_per_page: 9,
			current_page: curent_page,
			prev_text: '上一页',
			next_text: '下一页',
			callback: function( page_index, jq ) {
				if ( param.page ) {
					param.page = false;
					return;
				} else {
					param.data.p = page_index + 1;
					initialize( param );
				}
			}
		} );
	};

	function group_list( grouping ) {
		$( ".article_grouping > div.group_list" ).empty();
		$( ".group_more > option" ).not( ':first' ).remove();
		$( ".packet_select > option" ).not( ':first' ).remove();
		$( "select.group_more" ).addClass( 'hide' );
		var group_html = '',
			more_html = '',
			modal_op = '';
		if ( grouping.length > 0 ) {
			for ( var i in grouping ) {
				if ( i < 4 ) {
					group_html += '<span data-cgid="' + grouping[ i ].id + '"' + ( ( art_group_id == grouping[ i ].id ) ? ' class="green"' : '' ) + '>' + grouping[ i ].group_name + '</span>';
				} else {
					more_html += '<option value="' + grouping[ i ].id + '"' + ( ( art_group_id == grouping[ i ].id ) ? ' selected = "selected"' : '' ) + '>' + grouping[ i ].group_name + '</option>';
				}
				modal_op += '<option value="' + grouping[ i ].id + '">' + grouping[ i ].group_name + '</option>'
			}
		}

		if ( grouping.length > 4 ) {
			$( ".group_more" ).removeClass( 'hide' );
		}

		$( ".article_grouping > div.group_list" ).append( group_html );
		$( "select.group_more" ).append( more_html );
		$( "select.packet_select" ).append( modal_op );
		$( 'select.group_more,select.packet_select' ).selectpicker( 'refresh' );
	}

	initialize( param );
	/* ========== * 搜索 * ========== */
	content.find( '.search_btn' ).on( 'click', function() {
		param.data.p = 1;
		param.page = true;
		param.data.key = $.trim( $( '#search_text' ).val() );
		initialize( param );
	} );

	/* ==== 批量管理 ==== */
	content.find( '.batch_manager' ).click( function() {
		if ( $( this ).data( 'manager' ) ) {
			$( this ).data( 'manager', false );
			$( this ).text( '批量管理' );
			$( '.action_btn,.choice_num' ).addClass( 'hide' );
			$( '.article_grouping,.search,#upload_pictures,.altogether,.creat_graph' ).removeClass( 'hide' );
			content.find( '.print_masking' ).removeClass( 'fade in' );
			content.find( '.graph_item' ).removeClass( 'active' );
			content.find( '.action_btn > button' ).attr( 'disabled', true );
			content.find( '.choice_num' ).html( '点击选择要批量操作的图片' );
		} else {
			$( this ).data( 'manager', true );
			$( this ).text( '取消管理' );
			$( '.action_btn,.choice_num' ).removeClass( 'hide' );
			$( '.article_grouping,.search,#upload_pictures,.altogether,.creat_graph' ).addClass( 'hide' );
			content.find( '.print_masking' ).addClass( 'fade' );
			content.find( '.graph_item' ).addClass( 'active' );
		}
	} )

	/*选中图片*/
	content.on( 'click', '.print_masking', function() {
		if ( $( this ).hasClass( 'in' ) ) {
			$( this ).removeClass( 'in' ).find( 'span' ).addClass( 'hide' );
		} else {
			$( this ).addClass( 'in' ).find( 'span' ).removeClass( 'hide' );
		}
		if ( content.find( '.print_masking.fade.in' ).length > 0 ) {
			content.find( '.action_btn > button' ).removeAttr( 'disabled' );
			content.find( '.choice_num' ).html( '已选<span class="green total_number">' + content.find( '.print_masking.fade.in' ).length + '</span>篇图文' );
		} else {
			content.find( '.action_btn > button' ).attr( 'disabled', true );
			content.find( '.choice_num' ).html( '点击选择要批量操作的图文' );
		}
	} );

	/* ==== 分发状态、图文类型切换 ==== */
	content.on( 'change', 'select.scatter_select', function() {
		param.page = true;
		param.data.p = 1;
		param.data.send_bigwis = $( this ).val();
		initialize( param );
	} );
	// content.on( 'change', 'select.genre_select', function() {
	// 	param.page = true;
	// 	param.data.p = 1;
	// 	// param.data.is_show = $(this).val();
	// 	// picture_list(params);
	// } );

	/* ========== * 分组切换 * ========== */
	content.on( 'change', 'select.group_more', function() {
		if ( $( this ).val() != '' ) {
			$( '.group_list' ).children().removeClass( 'green' );
			$( '.group_more' ).addClass( 'green' );
			param.page = true;
			param.data.p = 1;
			param.data.custom_group_id = $( this ).val();
			initialize( param );
		}
	} );
	content.on( 'click', '.group_list > span', function() {
		if ( $( this ).hasClass( 'green' ) ) {
			return false;
		}
		if ( $( 'select.group_more' ).val() != '' ) {
			$( '.group_more' ).removeClass( 'green' );
			$( 'select.group_more' ).val( '' );
			$( 'select.group_more' ).selectpicker( 'refresh' );
		}
		$( this ).addClass( 'green' ).siblings().removeClass( 'green' );
		param.page = true;
		param.data.p = 1;
		param.data.custom_group_id = $( this ).data( 'cgid' );
		initialize( param );
	} );

	/* ========== * 移动分组 * ========== */
	content.find( ".action_group" ).click( function groupmove( e ) {
		e = e || event;
		e.stopPropagation();
		var groupData = groupManageConfig.userGroupData;
		var groupsHtml = '';

		var art_id = "";
		$( ".graph_list .print_masking" ).each( function() {
			if ( $( this ).hasClass( 'fade in' ) ) {
				var i = $( this ).parents( '.graph_item' ).index();
				if ( art_id.length > 1 ) {
					art_id += ",";
				}
				art_id += art_data[ i ].article_group;
			}
		} );

		if ( groupData.length < 1 ) {
			addGrouping( this, art_id );
			return;
		}
		groupsHtml += '<div image_id="' + art_id + '" class="category-tab" style="display: block;">';
		for ( i in groupData ) {
			if ( i == 0 ) {
				groupsHtml += '<div class="category" target_group="' + groupData[ i ].id + '"><div class="arrow"></div>' + groupData[ i ].group_name + '</div>';
			} else {
				groupsHtml += '<div class="category" target_group="' + groupData[ i ].id + '">' + groupData[ i ].group_name + '</div>';
			}
		}
		groupsHtml += '</div>';

		var left = 0,
			top = 0;

		var thisHeight = $( this ).outerHeight(),
			thisWidth = $( this ).outerWidth(),
			thisTop = $( this ).offset().top,
			thisLeft = $( this ).offset().left;
		left = thisLeft + thisWidth - thisWidth / 2 + 58;
		top = thisTop + thisHeight - thisHeight / 2 - 20;

		$( '.category-tab' ).remove();
		$( 'body' ).append( $( groupsHtml ).css( {
			left: left,
			top: top
		} ) );

		$( document ).bind( 'click.category', function() {
			$( '.category-tab' ).remove();
			$( document ).unbind( 'click.category' );
		} );
	} );

	content.on( 'click', '.move_btn', function( e ) {
		e = e || event;
		e.stopPropagation();
		var cd = $( this ).parents( '.graph_item' ).data( 'cd' );
		var groupData = groupManageConfig.userGroupData;

		if ( groupData.length < 1 ) {
			message.showWarning( '您还没有分组', message.showTime );
			return;
		}

		$( '#mobile_packet_m' ).modal( 'show' ).attr( 'data-cd', cd );
	} );
	$( '#mobile_packet_m' ).on( 'click', '.move_sure', function() {
		var _cd = $( this ).parents( '#mobile_packet_m' ).data( 'cd' );
		var gid = $( 'select.packet_select' ).val();
		if ( gid == '' ) {
			message.showWarning( '您还没有选择分组', message.showTime );
		} else {
			cg( _cd, gid );
			$( '#mobile_packet_m' ).modal( 'hide' );
		}
	} )

	$( document ).on( 'click', '.category-tab .category', cg );

	function addGrouping( obj, img_id ) {
		var _this = $( obj );
		var type = event.srcElement.type;

		$( "body" ).append( '<div class="add_grouping">' +
			'<img src="' + route.resPath + '/images/Triangle-up.png">' +
			'<p>您还没有分组，请添加分组</p>' +
			'<input type="text" value="" maxlength="30" class="sure_val"><br/>' +
			'<button type="button" class="btn-success sure">确定</button>' +
			'<button type="button" class="btn-default btn_cancel" onclick="$(this).parent().remove()">取消</button>' +
			'</p>' +
			'</div>' );
		$( '.add_grouping' ).css( {
			left: _this.offset().left - $( '.add_grouping' ).width() / 2 + 40,
			top: _this.offset().top + $( '.add_grouping' ).height() / 3,
		} );

		$( '.sure_val' ).focus();
		$( '.sure_val' ).on( 'keyup', function( e ) {
			e = e || event;
			if ( e.keyCode == 13 ) {
				//判断是否按下的enter按键(回车键)
				$( '.add_grouping > .sure' ).trigger( 'click' );
			}
		} );

		$( '.add_grouping > .sure' ).click( function() {
			var _group = $( '.sure_val' ).val();
			if ( _group ) {
				data_art_id = img_id;
				$( this ).parent().remove();
				groupManage.commonAddGroup( _group );
			} else {
				message.show( '请输入分组名', 1500 );
				$( '.sure_val' ).focus();
			}
		} );
		/**
		 * 点击其他地方隐藏
		 */
		$( document ).bind( 'click.add_grouping', function( e ) {
			var e = e || window.event; //浏览器兼容性 
			var elem = e.target || e.srcElement;
			while ( elem ) { //循环判断至跟节点，防止点击的是div子元素 
				if ( elem.className && elem.className == 'add_grouping' ) {
					return;
				}
				elem = elem.parentNode;
			}

			$( ".add_grouping" ).remove(); //点击的不是div或其子元素 
			$( document ).unbind( "click.add_grouping" );
		} );
	}

	function cg( s, d ) {
		if ( d ) {
			var cd = s,
				cgid = d;
		} else {
			var cd = $( this ).parent().attr( 'image_id' ).split( ',' ),
				cgid = $( this ).attr( 'target_group' );
		}

		$.ajax( {
			type: 'post',
			url: InterFace.MYMPNEWS.MOVE_MPNEWS_CUSTOMS,
			data: {
				mpnews_custom_id: cgid,
				article_group_cd: cd,
			},
			success: function( data ) {
				var data = typeof data === 'string' ? $.parseJSON( data ) : data;
				if ( data.ret == 0 ) {
					message.show( '操作成功！', message.showTime );
					if ( !!param.data.custom_group_id ) {
						group_first_load = true;
						param.page = true;
						initialize( param );
					} else {
						group_id();
					}
				} else {
					message.showWarning( '您还没有分组或者该图文已存在您唯一分组中', message.showTime );
				}
			}
		} )
	};

	/* ========== * 分组文章数同步 * ========== */
	function group_id() {
		$.ajax( {
			type: 'post',
			dataType: 'json',
			url: InterFace.MYMPNEWS.GET_FULL_MSG,
			success: function( data ) {
				var customs = data.data.customs;
				for ( var i in customs ) {
					$( '[groupid=\"' + customs[ i ].id + '\"]' ).find( '.battery-number' ).text( customs[ i ].group_num );
				}
			}
		} );
	}

	/* ========== * 同步 * ========== */
	var acount_info,
		public_json = {};
	content.on( 'click', '.synchro', function() {
		$( "#public_list" ).modal( 'show' );
		public_json.mp_cd = $( this ).siblings( 'input' ).attr( 'groupid' );
		public_json.titles = $( this ).siblings( 'input' ).data( 'title' );
	} );
	definedCallback.sure = function( data ) {
		acount_info = data;
		if ( data.verify_type_info == '-1' ) {
			gzh_login( synchro_j );
		} else {
			synchro_j();
		}
	}

	function gzh_login( fn ) {
		var authordata = {
			login_account: acount_info.login_account,
			appid: acount_info.app_id
		}
		if ( !acount_info.login_account ) {
			authordata.isNewAuthor = !0
		} else {
			authordata.isNewAuthor = 0;
		}
		bwAuthor.doAuthorOperate( authordata, function( data ) {
			acount_info.login_account = data.login_account;
			fn();
		} );
	}

	function synchro_j() {
		message.show( '同步中...', message.showTime );
		if ( acount_info.verify_type_info == '-1' ) {
			$.ajax( {
				type: 'post',
				url: InterFace.COMMON.MPNEWS_ASYNSIMSEND,
				data: {
					login_account: acount_info.login_account,
					mp_cd: public_json.mp_cd,
					titles: public_json.titles,
				},
				success: function( data ) {
					var data = typeof data === 'string' ? $.parseJSON( data ) : data;
					if ( data.ret != 99999 ) {
						message.showWarning( data.msg, message.showTime );
					} else {
						message.hide();
					}
				}
			} );
		} else {
			$.ajax( {
				type: 'post',
				url: InterFace.COMMON.MPNEWS_ASYNSEND,
				data: {
					app_id: acount_info.app_id,
					mp_cd: public_json.mp_cd,
					titles: public_json.titles,
				},
				success: function( data ) {
					var data = eval( '(' + data + ')' );
					if ( data.ret != 99999 ) {
						message.showWarning( data.msg, message.showTime );
					} else {
						message.hide();
					}
				}
			} );
		}
	}

	/* ========== * 删除图文 * ========== */
	content.on( 'click', '.delete_single,.item_delete,.delete_multi', function( e ) {
		e.stopPropagation();
		content.find( '.more_moadl' ).removeClass( 'show' );
		var $t = $( this );
		var checkedArray = new Array();
		if ( $t.hasClass( 'delete_multi' ) ) {
			$( ".graph_list .print_masking" ).each( function() {
				if ( $( this ).hasClass( 'fade in' ) ) {
					var i = $( this ).parents( '.graph_item' ).index();
					checkedArray.push( art_data[ i ].article_group );
				}
			} );
		} else {
			if ( $t.hasClass( 'delete_single' ) ) {
				$t.parent().addClass( 'show' );
			}
			checkedArray.push( $t.parents( '.graph_item' ).data( 'cd' ) );
		}
		bc.deleteConfirmShowBottom( {
			obj: this,
			type: 'post',
			url: InterFace.MYMPNEWS.DELETE_MPNEWS,
			text: '删除后不会影响已分发以及已发送的图文消息，确定删除该素材？',
			skewX: -60,
			param: {
				article_group_cd: checkedArray
			},
			'fun': function( data ) {
				var data = typeof data === 'string' ? $.parseJSON( data ) : data;
				if ( data.ret == 0 ) {
					if ( checkedArray.length == 9 ) {
						if ( param.data.p != 1 ) {
							param.data.p -= 1;
						}
					}
					param.page = true;
					initialize( param );
					message.show( '删除成功', message.showTime );
					content.find( '.more_moadl' ).removeClass( 'show' );
				} else {
					message.showWarning( data.msg, message.showTime );
				}
			},
			cancel: function( data ) {
				content.find( '.more_moadl' ).removeClass( 'show' );
			}
		} );
	} );

	/* ========== * 复制 * ========== */
	content.on( 'click', '.copy_a', function() {
		var cd = $( this ).parents( '.graph_item' ).data( 'cd' );
		$.ajax( {
			type: 'get',
			url: InterFace.MYMPNEWS.CPMPNEWS,
			data: {
				article_group: cd
			},
			success: function( data ) {
				var data = typeof data === 'string' ? $.parseJSON( data ) : data;
				if ( data.ret == 0 ) {
					message.show( '复制成功', message.showTime );
					initialize( param );
				} else {
					message.showWarning( data.msg, message.showTime );
				}
			}
		} )
	} );
	/* ========== * 预览 * ========== */
	content.on( 'click', '.preview', function() {
		sp.doArtSendPreview( {
			articleGroup: $( this ).parents( '.graph_item' ).data( 'cd' ),
			articleTitle: $( this ).parents( '.graph_item' ).data( 'title' )
		} );
	} );
	/* ========== * 分发 * ========== */
	// content.on( 'click', '.release_btn', function() {
	// 	var cd = $( this ).parents( '.graph_item' ).data( 'cd' );
	// 	$('#release_modal').modal('show')
	// } );
} );